//
//  YYEHMStatusPictureView.swift
//  weibo14
//
//  Created by mac on 16/3/8.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

private let ID = "UICollectionViewCell"

let itemMargin: CGFloat = 5

// 1. 计算出每一张图片多大
let itemWH = CGFloat(Int(SCREENW - 2 * YYEStatusCellMargin - 2 * itemMargin)/3)

class YYEStatusPictureView: UICollectionView {
    
    
    // 增加一个属性 这个属性沟通用 传过来的是数组 根据数据的多小去决定view的大小
    var picUrls: [YYEStatusPictureInfo]? {
        didSet{

            // 去更新自己的size约束
            // 考虑到复用的问题  用updda
            // 有了数据
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(self.sizeWithCount(picUrls?.count ?? 0))
                
                
                
            // 刷新数据
             self.reloadData()
                
                
            }
            
        }
    
    }
    
    

    override  init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
    
         super.init(frame: frame, collectionViewLayout: layout)
    
         setupUI()
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        self.backgroundColor = UIColor(white: 239/255, alpha: 1)
        
        registerClass(YYEStatusPictureViewCell.self, forCellWithReuseIdentifier: ID)
        

        // 设置条目的大小
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        // 设置最小间距
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin

        
        self.dataSource = self
        self.delegate = self

    }
    
    // 根据个数计算
    private func sizeWithCount(count:Int) -> CGSize {
        
        // 在这个变 -------改变
        if count == 1 {
        
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(picUrls!.first?.thumbnail_pic) {

            
                let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
                
                let size = CGSizeMake(image.size.width * 4, image.size.height * 4)
                
                layout.itemSize = size
                
                return size
            }
        }
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: itemWH, height: itemWH)

        // 计算行看列的个数
        let col = count == 4 ? 2: count > 3 ? 3 : count
        let row = (count - 1) / 3 + 1
        
        let width =  CGFloat(col) * itemWH + CGFloat((col - 1)) * itemMargin
        let height = CGFloat(row) * itemWH + CGFloat((row - 1)) * itemMargin
        
        return CGSize(width: width, height: height)
    }
    

}
extension YYEStatusPictureView:UICollectionViewDataSource {

    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ID, forIndexPath: indexPath) as! YYEStatusPictureViewCell
        
        cell.statusPictureInfo = self.picUrls![indexPath.item]
        
        cell.backgroundColor = UIColor.purpleColor()
        
        return cell
        
    }

}

class YYEStatusPictureViewCell: UICollectionViewCell {

    
    
    // YYEStatusPictureInfo
    var statusPictureInfo:YYEStatusPictureInfo?{
    
        didSet{
                guard let str = statusPictureInfo?.thumbnail_pic else {
                return
            }
            imageView.sd_setImageWithURL(NSURL(string:str), placeholderImage:UIImage(named: "timeline_image_placeholder"))
        }
    
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(imageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(contentView)
        }
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var imageView:UIImageView = {
    
       let view:UIImageView = UIImageView()
        // 设置imageView的内容模式
        view.contentMode = .ScaleAspectFill
        // 把超出控件的内容给删掉
        view.clipsToBounds = true
        return view
    }()
    
}






extension YYEStatusPictureView: UICollectionViewDelegate {
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        /**
         SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
         browser.sourceImagesContainerView = self; // 原图的父控件
         browser.imageCount = self.photoItemArray.count; // 图片总数
         browser.currentImageIndex = button.tag;
         browser.delegate = self;
         [browser show];
         
         */
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = picUrls!.count
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
    }
}

extension YYEStatusPictureView: SDPhotoBrowserDelegate {
    
    
    /// 返回占位图片的代理方法
    ///
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        // 1. 取到 index 对应的cell
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as? YYEStatusPictureViewCell
        // 2. 取到cell的imageView --> imageView.image
        return cell?.imageView.image
    }
    
    /// 返回高质量的图片的url

    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        //     NSString *urlStr = [[self.photoItemArray[index] thumbnail_pic] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
        let urlStr = picUrls![index].thumbnail_pic?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle") ?? ""
        return NSURL(string: urlStr)
        
    }

}















